package com.xiaoyun.alllearning.service.impl;

import com.xiaoyun.alllearning.exception.BusinessException;
import com.xiaoyun.alllearning.exception.ErrorCodeEnum;
import com.xiaoyun.alllearning.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;

@Service("localFileServiceImpl")
@Slf4j
public class FileServiceImpl implements FileService {
    public static final String BUCKET = "uploads";

    @Override
    public void upload(InputStream inputStream, String filename) {
        String storagePath = BUCKET + "/" + filename;

        try (InputStream innerInputStream = inputStream;
             FileOutputStream outputStream = new FileOutputStream(new File(storagePath));
        ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = innerInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            //冲刷流
            outputStream.flush();
        } catch (Exception e) {
            log.error("文件上传失败:{}", e);
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }

    }

    @Override
    public void upload(File file) {
        try {
            upload(new FileInputStream(file), file.getName());
        } catch (Exception e) {
            log.error("文件上传失败:{}", e);
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }
    }
}
